package cn.fulong.frame.service.impl;

import cn.fulong.frame.service.ComputeData;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service("computeDataByGroup")
public class ComputeDataByGroup extends ComputeData {

    @Override
    public Map execute(Map datas, Map compute) throws Exception {
        String group = compute.get("group").toString();
        System.out.println(group);

        String dsName = compute.get("dsName").toString();
        List<Map<String, Object>> dataset = (List<Map<String, Object>>) datas.get(dsName);

        String name = compute.get("name").toString();
        Map result = new HashMap();

        String code = "";
        Map map = new HashMap();
        List list = new ArrayList();
        for (Map<String, Object> record : dataset) {
            String nextCode = (String) record.get(group);
            record.remove(group);
            if (code.equals(nextCode)) {
                //和上一个在同一分组
                //加入code对应的数组
                list.add(record);
            } else {
                //和上一个不同分组
                //把上一个数组加入map，新建一个数组
                if (list.size() > 0) {
                    map.put(code, list);
                }
                code = nextCode;
                list = new ArrayList();
                list.add(record);
            }
        }
        map.put(code, list);

        result.put(name, map);
        return result;
    }
}
